package com.aek.ebey.sys.service.impl;

import com.aek.ebey.sys.mapper.SysModuleMapper;
import com.aek.ebey.sys.model.SysModule;
import com.aek.ebey.sys.model.SysTenant;
import com.aek.ebey.sys.model.custom.ModuleCustom;
import com.aek.ebey.sys.service.SysModuleService;
import com.aek.ebey.sys.service.SysTenantService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.aek.common.core.base.BaseServiceImpl;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统模块表 服务实现类
 * </p>
 *
 * @author aek
 * @since 2017-05-06
 */
@Service
public class SysModuleServiceImpl extends BaseServiceImpl<SysModuleMapper, SysModule> implements SysModuleService {

	@Autowired
	private SysModuleMapper moduleMapper;

	@Autowired
	private SysTenantService tenantService;

	@Override
	public List<SysModule> findAllModuleWithNotDel() {

		Wrapper<SysModule> wrapper = new EntityWrapper<SysModule>();
		wrapper.eq("del_flag", false);
		wrapper.eq("enable", true);
		List<SysModule> modules = moduleMapper.selectList(wrapper);

		for (SysModule module : modules) {
			module.setCoustom(JSON.parseObject(module.getCustomData(), ModuleCustom.class));
		}
		return modules;
	}

	@Override
	public List<SysModule> findModuleByTenantIdWithCan(Long tenantId) {
		SysTenant tenant = this.tenantService.selectById(tenantId);
		// 当前租户类型
		Integer tenantType = tenant.getTenantType();

		List<SysModule> modules = this.findAllModuleWithNotDel();
		Iterator<SysModule> it = modules.iterator();

		// 根据租户类型判断当前租户是否可以拥有该模块
		while (it.hasNext()) {
			SysModule module = it.next();

			ModuleCustom custom = module.getCoustom();
			List<Integer> tenantTypes = custom.getTenantType();

			// 是否为所有类型租户默认拥有模块
			boolean defaultExist = custom.getDefaultExist();
			if (defaultExist) {
				continue;
			}

			if (!tenantTypes.contains(tenantType)) {
				it.remove();
			}
		}
		return modules;
	}

	@Override
	public boolean isDefaultExist(Long moduleId) {
		SysModule module = this.selectById(moduleId);
		ModuleCustom moduleCustom = JSON.parseObject(module.getCustomData(), ModuleCustom.class);
		return moduleCustom.getDefaultExist();
	}

}
